package com.baicaixiaozhan.springsecurityswaggerdemo.pojo;

import com.google.common.collect.Sets;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Set;
import java.util.stream.Collectors;

import static com.baicaixiaozhan.springsecurityswaggerdemo.pojo.PersonPermission.*;

/**
 * DESC: 用户权限
 *
 * @author : baicaixiaozhan
 * @since : 2020-11-05
 */
public enum PersonRole {
    // 开发
    DEVELOPMENT(Sets.newHashSet(DEVELOPMENT_READ, DEVELOPMENT_TEST)),
    // 管理
    ADMIN(Sets.newHashSet(DEVELOPMENT_READ, DEVELOPMENT_TEST, ADMIN_READ, ADMIN_TEST)),
    // 消费者(用户)
    CONSUMER(Sets.newHashSet(CONSUMER_READ));

    private final Set<PersonPermission> permissions;

    PersonRole(Set<PersonPermission> permissions) {
        this.permissions = permissions;
    }

    public Set<PersonPermission> getPermissions() {
        return permissions;
    }

    /**
     * 获取一组 赋予权限的 stores (simple)
     * @return
     */
    public Set<SimpleGrantedAuthority> getGrantedAuthorities() {
        final Set<SimpleGrantedAuthority> authorities = getPermissions().stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getPermission()))
                .collect(Collectors.toSet());
        authorities.add(new SimpleGrantedAuthority("ROLE_" + this.name()));
        return authorities;
    }
}
